package com.zhxy.util.mail;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;


public class BasicMailService implements IMailService {
	
	private String host;
	
	private String user;
	
	private String password;
	
	private boolean debug;
	
	private Session session;

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}
	
	@Override
	public MimeMessage createMimeMessage() {
		return new MimeMessage(getSession());
	}

	@Override
	public void sendMimeMessage(MimeMessage message) {
		
		Transport transport = null;
		try {
			
			transport = session.getTransport("smtp");
			transport.connect(host, user, password);
			transport.sendMessage(message, message.getAllRecipients());
			
		} catch (MessagingException e) {
			throw new MailException(e);
		} finally {
			if (transport != null && transport.isConnected()) {
				try {
					transport.close();
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
 	}
	
	protected Session getSession() {
		
		if (session == null) {
			synchronized (this) {
				if (session == null) {
					Properties prop = new Properties();
					if (user != null || password != null)
						prop.put("mail.smtp.auth", "true");
					
					session = Session.getDefaultInstance(prop);
					session.setDebug(debug);
				}
			}
		}
		
		return session;
	}

}
